<?php
/**
 * OneBase 安装逻辑
 * @author 王勇程 <laughskydragon@qq.com>
 * @date 2017-02-10
 */

namespace app\install\logic;

use think\facade\Db;
use think\facade\Config;

/**
 * 安装逻辑
 */
class Install
{
    
    /**
     * 检查安装数据
     */
    public function checkData($data)
    {
        // 检测管理员信息
        if (empty($data['admin_username']) || empty($data['admin_password']) || empty($data['admin_email'])) {
            return ['code' => 0, 'msg' => '请填写完整管理员信息'];
        }
        
        if ($data['admin_password'] != $data['admin_repassword']) {
            return ['code' => 0, 'msg' => '确认密码和密码不一致'];
        }
        
        // 检测数据库配置
        if (empty($data['db_type']) || empty($data['db_hostname']) || empty($data['db_database']) || empty($data['db_username'])) {
            return ['code' => 0, 'msg' => '请填写完整的数据库配置'];
        }
        
        return ['code' => 1, 'msg' => '数据验证通过'];
    }
    
    /**
     * 检查安装数据（兼容旧版本）
     */
    public function check($db = null, $admin = null)
    {
        
        // 检测管理员信息
        if (!is_array($admin) || empty($admin[0]) || empty($admin[1]) || empty($admin[3])) {

            return "请填写完整管理员信息";

        } else if ($admin[1] != $admin[2]) {

            return "确认密码和密码不一致";
        }
        
        // 检测数据库配置
        if (!is_array($db) || empty($db[0]) ||  empty($db[1]) || empty($db[2]) || empty($db[3])) {

            return "请填写完整的数据库配置";
        }
        
        return true;
    }
    
    /**
     * 安装（新版本）
     */
    public function install($data)
    {
        try {
            // 准备管理员信息
            $info = [
                'username' => $data['admin_username'],
                'password' => $data['admin_password'],
                'repassword' => $data['admin_repassword'],
                'email' => $data['admin_email']
            ];

            // 准备数据库配置
            $db_config = [
                'type' => $data['db_type'],
                'hostname' => $data['db_hostname'],
                'database' => $data['db_database'],
                'username' => $data['db_username'],
                'password' => $data['db_password'] ?? '',
                'hostport' => $data['db_hostport'] ?? '3306',
                'prefix' => $data['db_prefix'] ?? 'ob_'
            ];

            // 创建数据库
            $dbname = $db_config['database'];
            $database_name = $db_config['database'];
            unset($db_config['database']);

            // 注入 install_raw 连接配置（不带 database，用于创建库）
            $databaseCfg = Config::get('database');
            $databaseCfg['connections']['install_raw'] = array_merge($db_config, [
                'charset' => 'utf8',
            ]);
            Config::set($databaseCfg, 'database');

            // 使用 install_raw 连接创建数据库
            $db_object = Db::connect('install_raw', true);
            $sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET utf8";
            
            if (!$db_object->execute($sql)) {
                return ['code' => 0, 'msg' => '创建数据库失败'];
            }

            // 创建数据表（注入 install 连接，带 database）
            $db_config['database'] = $database_name;
            $databaseCfg['connections']['install'] = array_merge($db_config, [
                'charset' => 'utf8',
            ]);
            Config::set($databaseCfg, 'database');

            $db_object_database = Db::connect('install', true);

            if (!create_tables($db_object_database, $db_config['prefix'])) {
                return ['code' => 0, 'msg' => '创建数据表失败'];
            }

            // 注册超级帐号
            $auth = build_auth_key();
            if (!register_administrator($db_object_database, $db_config['prefix'], $info, $auth)) {
                return ['code' => 0, 'msg' => '注册超级管理员失败'];
            }

            // 创建配置文件
            if (!write_config($db_config, $auth)) {
                return ['code' => 0, 'msg' => '创建配置文件失败'];
            }
            
            return ['code' => 1, 'msg' => '安装完成'];
            
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '安装失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 安装（兼容旧版本）
     */
    public function installOld($db = null, $admin = null)
    {
        $info = [];

        list($info['username'], $info['password'], $info['repassword'], $info['email']) = $admin;

        $db_config = [];

        list($db_config['type'], $db_config['hostname'], $db_config['database'], $db_config['username'], $db_config['password'],
             $db_config['hostport'], $db_config['prefix']) = $db;

        // 创建数据库（原始连接不带 database）
        $dbname = $db_config['database'];
        $database_name = $db_config['database'];
        unset($db_config['database']);

        // 注入 install_raw 连接配置
        $databaseCfg = Config::get('database');
        $databaseCfg['connections']['install_raw'] = array_merge($db_config, [
            'charset' => 'utf8',
        ]);
        Config::set($databaseCfg, 'database');

        // 使用 install_raw 连接创建数据库
        $db_object = Db::connect('install_raw', true);
        $sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET utf8";

        if (!$db_object->execute($sql)) { return "创建数据库失败"; }

        // 创建数据表（注入 install 连接，带 database）
        $db_config['database'] = $database_name;
        $databaseCfg['connections']['install'] = array_merge($db_config, [
            'charset' => 'utf8',
        ]);
        Config::set($databaseCfg, 'database');

        $db_object_database = Db::connect('install', true);

        if (!create_tables($db_object_database, $db_config['prefix'])) { return "创建数据表失败"; }

        // 注册超级帐号
        $auth  = build_auth_key();

        if (!register_administrator($db_object_database, $db_config['prefix'], $info, $auth)) { return "注册超级管理员失败"; }

        // 创建配置文件
        if (!write_config($db_config, $auth)) { return "创建配置文件失败"; }

        return true;
    }
}
